#include <mutex>
#include <thread>
#include <iostream>
using namespace std;

template <class T>
class myshare_ptr
{
private:
    T *_ptr;
    int *_count;
    mutex *_mutex;

public:
    myshare_ptr(T *ptr)
        : _ptr(ptr), _count(new int(1)), _mutex(new mutex)
    {
    }

    myshare_ptr(const myshare_ptr<T> &sp)
        : _ptr(sp._ptr), _count(sp._count), _mutex(sp._mutex)
    {
        addCount();
    }
    ~myshare_ptr()
    {
        release(); // 析构时应当解绑
    }

    void release()
    {
        _mutex->lock();

        bool deleteflag=false;

        if (*_count && (--*(_count)) == 0)
        {
            delete _count;
            delete _ptr;
            deleteflag = true;
        }

        _mutex->unlock();
        if (deleteflag)
        {
            delete _mutex;
        }
    }

    void addCount()
    {
        _mutex->lock();
        ++(*_count);
        _mutex->unlock();
    }

    void showCount()
    {
        cout << (*_ptr) << " " << (*_count) << endl;
    }

    myshare_ptr &operator=(const myshare_ptr<T> &sp)
    {
        if (_ptr != sp._ptr)
        { 
            // 防止自我赋值
            release();
            _ptr = sp._ptr;
            _count = sp._count;
            _mutex = sp._mutex;
            addCount();
        }
        return *this;
    }

    T& operator* ()
    {
        return *_ptr;
    }

    T* operator->()
    {
        return _ptr;
    }

};

int main()
{
    myshare_ptr<char> a(new char('a'));
    a.showCount();
    
    myshare_ptr<char> b(a);
    b.showCount();
    
    myshare_ptr<char> c(new char('b'));
    c.showCount();
    
    c=b;
    c.showCount();
    
    return 0;
}
